#include"server.h"

using namespace std;

void process(server*l,int sock){
    l->handle(sock);
}
server::server(unsigned short p,string i):port(p),ip(inet_addr(i.c_str())){
}

void server::start()
{
    server_sock=socket(PF_INET,SOCK_STREAM,0);
    if(server_sock==-1) error("socket");

    struct sockaddr_in serv_adr;

    bzero(&serv_adr,sizeof(serv_adr));
    serv_adr.sin_port=htons(port);
    serv_adr.sin_family=AF_INET;
    serv_adr.sin_addr.s_addr=htonl(ip);

    if(bind(server_sock,(sockaddr*)&serv_adr,sizeof(serv_adr))==-1)
    error("bind");

    if(listen(server_sock,10)==-1) error("listen");
    cout<<"服务器开始监听\n";
    cout<<port<<endl;

    thread t(thread1);
    t.detach();
}

void server::run()
{
    while(true){
        sockaddr_in cln_addr;
        socklen_t sz_cln_addr=sizeof(cln_addr);
        int cln_sock=accept(server_sock,(sockaddr*)&cln_addr,&sz_cln_addr);
        if(cln_sock==-1) error("socket");
        {
            lock_guard<mutex> lock_a(m);
            sock_clns.insert(cln_sock);
        }
        thread cln_handle(&server::handle,this,cln_sock);
        //if(cln_handle.joinable())
        cln_handle.detach();
        cout<<"客户端"<<cln_sock<<" 连接服务器，线程 "<<cln_handle.get_id()<<",ip: "<<inet_ntoa(cln_addr.sin_addr)<<endl;
    }
}

server::~server()
{
    cout<<"退出"<<endl;
    close(server_sock);
}
void server::handle(int cln)
{
    char msg[BUF_SIZE]={0};
   int len=0;
    while((len=recv(cln,msg,sizeof(msg),0))!=0){
        msg[len]=0;
       // cout<<msg<<endl;
        for(int i:sock_clns){
        if(i!=cln) send(i,msg,len,0);
        }
    }
    {
     lock_guard<mutex> lock_a(m);
     sock_clns.erase(cln);
    }
     close(cln);
}

void server::thread1()
{
    cout << "server::thread()\n";
}

int main(){
    server s(9900);
    s.start();
    s.run();
}
